package com.ssy.lingxi.search.controller.pc;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.manage.ShopTypeEnum;
import com.ssy.lingxi.common.constant.member.RoleTypeEnum;
import com.ssy.lingxi.common.controller.BaseController;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.search.api.model.request.CommoditySearchRequest;
import com.ssy.lingxi.search.api.model.request.MroSearchRequest;
import com.ssy.lingxi.search.api.model.request.channel.ChannelCommoditySearchRequest;
import com.ssy.lingxi.search.api.model.response.CommoditySearchResponse;
import com.ssy.lingxi.search.api.model.response.MroCommoditySearchResponse;
import com.ssy.lingxi.search.api.model.response.channel.ChannelCommoditySearchResponse;
import com.ssy.lingxi.search.service.IChannelShopService;
import com.ssy.lingxi.search.service.ICommodityService;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author jw.chen
 * @version 2.0.0
 * @menu: 店铺商城
 * 店铺商城类
 * @date 2020/8/1
 */
@RestController
@RequestMapping("/search/shop/mro")
public class MroController extends BaseController {

    @Resource
    private ICommodityService commodityService;

    @Resource
    private IChannelShopService channelService;


    @Resource
    private IRedisStringUtils redisStringUtils;


    /**
     * 查询商品列表
     *
     * @param mroSearchRequest
     * @return
     */
    @RequestMapping(value = "/getCommodityList", method = RequestMethod.POST)
    public Wrapper<PageData<MroCommoditySearchResponse>> searchCommodityList(@RequestBody MroSearchRequest mroSearchRequest) {
        Long shopId = this.getHeadersShopId();
        CommoditySearchRequest commoditySearchRequest = this.modelMapper.map(mroSearchRequest, CommoditySearchRequest.class);
        commoditySearchRequest.setShopId(shopId);

        //判断是否已登录
        if (this.isLogin()) {
            UserLoginCacheDTO sysUser = this.getSysUser();
            commoditySearchRequest.setLoginMemberId(sysUser.getMemberId());
            commoditySearchRequest.setLoginMemberRoleId(sysUser.getMemberRoleId());
        }

        //渠道商城参数
        Long channelMemberId = mroSearchRequest.getChannelMemberId();
        Long channelMemberRoleId = mroSearchRequest.getChannelMemberRoleId();

        return channelConditionNotNull(channelMemberId, channelMemberRoleId)
                ? channelSearch(mroSearchRequest, shopId, channelMemberId, channelMemberRoleId)
                : shopSearch(commoditySearchRequest);
    }

    /**
     * 企业商城
     *
     * @param commoditySearchRequest
     * @return
     */
    private Wrapper<PageData<MroCommoditySearchResponse>> shopSearch(CommoditySearchRequest commoditySearchRequest) {
        List<MroCommoditySearchResponse> mroCommoditySearchResponseList;
        PageData<CommoditySearchResponse> pageData = commodityService.searchCommodityList(commoditySearchRequest, true, false);
        return Wrapper.success(new PageData<>(pageData.getTotalCount(), pageData
                .getData()
                .stream()
                .map(commoditySearchResponse -> {
                    MroCommoditySearchResponse mroCommoditySearchResponse = new MroCommoditySearchResponse();
                    BeanUtil.copyProperties(commoditySearchResponse, mroCommoditySearchResponse);
                    return mroCommoditySearchResponse;
                }).collect(Collectors.toList())));
    }

    /**
     * 渠道商城
     *
     * @param mroSearchRequest
     * @param shopId
     * @param channelMemberId
     * @param channelMemberRoleId
     * @return
     */
    private Wrapper<PageData<MroCommoditySearchResponse>> channelSearch(MroSearchRequest mroSearchRequest, Long shopId, Long channelMemberId, Long channelMemberRoleId) {
        List<MroCommoditySearchResponse> mroCommoditySearchResponseList;
        if (channelMemberId < 0 || channelMemberRoleId < 0) {
            throw new BusinessException(ResponseCode.SEARCH_CHANNEL_NOT_EXIST);
        }
        //获取登录用户信息
        UserLoginCacheDTO sysUser = this.getSysUser();
        Long loginUserMemberId = sysUser.getMemberId();
        Long loginUserMemberRoleId = sysUser.getMemberRoleId();
        //参数
        ChannelCommoditySearchRequest channelCommoditySearchRequest = this.modelMapper.map(mroSearchRequest, ChannelCommoditySearchRequest.class);
        channelCommoditySearchRequest.setShopId(shopId);

        //判断是否登录自己的渠道商城
        checkIfLoginSeifChannelShop(channelMemberId, channelMemberRoleId, sysUser, loginUserMemberId, loginUserMemberRoleId, channelCommoditySearchRequest);

        //通过商城id查找商城类型
        Integer type = ShopTypeEnum.CHANNEL.getCode();
        String shopRedis = redisStringUtils.hGet(Constants.REDIS_KEY_SHOP, String.valueOf(shopId), Constants.REDIS_PLATFORM_MANAGE_INDEX);
        if (StringUtils.isNotEmpty(shopRedis)) {
            JSONObject jsonObject = JSONUtil.parseObj(shopRedis);
            type = jsonObject.getInt("type");
        }
        PageData<ChannelCommoditySearchResponse> pageData = channelService.searchCommodityList(sysUser, channelCommoditySearchRequest, true, ShopTypeEnum.CHANNEL_SCORE.getCode().equals(type));
        mroCommoditySearchResponseList = pageData
                .getData()
                .stream().
                map(channelCommoditySearchResponse -> {
                    MroCommoditySearchResponse mroCommoditySearchResponse = new MroCommoditySearchResponse();
                    BeanUtil.copyProperties(channelCommoditySearchResponse, mroCommoditySearchResponse);
                    return mroCommoditySearchResponse;
                }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(pageData.getTotalCount(), mroCommoditySearchResponseList));
    }

    /**
     * 判断是否登录自己的渠道商城
     * @param channelMemberId
     * @param channelMemberRoleId
     * @param sysUser
     * @param loginUserMemberId
     * @param loginUserMemberRoleId
     * @param channelCommoditySearchRequest
     */
    private void checkIfLoginSeifChannelShop(Long channelMemberId, Long channelMemberRoleId, UserLoginCacheDTO sysUser, Long loginUserMemberId, Long loginUserMemberRoleId, ChannelCommoditySearchRequest channelCommoditySearchRequest) {
        if (channelMemberId.equals(loginUserMemberId) && channelMemberRoleId.equals(loginUserMemberRoleId)) {
            //判断当前登录用户是供应商角色还是采购商角色
            Integer memberRoleType = sysUser.getMemberRoleType();
            if (RoleTypeEnum.SERVICE_PROVIDER.getCode().equals(memberRoleType)) {
                Long childChannelMemberId = channelCommoditySearchRequest.getChildChannelMemberId();
                Long childChannelMemberRoleId = channelCommoditySearchRequest.getChildChannelMemberRoleId();
                if (childChannelMemberId == null || childChannelMemberId < 0 || childChannelMemberRoleId == null || childChannelMemberRoleId < 0) {
                    throw new BusinessException(ResponseCode.SEARCH_CHILD_CHANNEL_NOT_EXIST);
                }
                channelCommoditySearchRequest.setChildChannelMemberId(childChannelMemberId);
                channelCommoditySearchRequest.setChildChannelMemberRoleId(childChannelMemberRoleId);
            } else {
                channelCommoditySearchRequest.setChildChannelMemberId(loginUserMemberId);
                channelCommoditySearchRequest.setChildChannelMemberRoleId(loginUserMemberRoleId);
            }
        } else {
            List<Long> upperChannelMemberIds = sysUser.getUpperChannelMemberIds();
            if (upperChannelMemberIds.contains(channelMemberId)) {
                channelCommoditySearchRequest.setChildChannelMemberId(loginUserMemberId);
                channelCommoditySearchRequest.setChildChannelMemberRoleId(loginUserMemberRoleId);
            } else {
                throw new BusinessException(ResponseCode.SEARCH_JOIN_UPPER_CHANNEL_NOT_EXIST);
            }
        }
    }

    /**
     * 校验渠道商城的搜索条件是否为为空
     *
     * @param channelMemberId
     * @param channelMemberRoleId
     * @return
     */
    private Boolean channelConditionNotNull(Long channelMemberId, Long channelMemberRoleId) {
        return Objects.nonNull(channelMemberId) && Objects.nonNull(channelMemberRoleId);
    }


}
